package com.jvyou.app.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jvyou.app.common.domain.entity.User;
import com.jvyou.app.common.domain.model.LoginUser;
import com.jvyou.app.common.domain.model.PageResult;
import com.jvyou.app.common.enums.HttpCodeEnum;
import com.jvyou.app.common.exception.AppException;
import com.jvyou.app.common.utils.orm.WrapperTool;
import com.jvyou.app.common.utils.value.ValueUtil;
import com.jvyou.app.ds.constants.UserType;
import com.jvyou.app.ds.domain.dto.LessonDto;
import com.jvyou.app.ds.domain.entity.*;
import com.jvyou.app.ds.mapper.*;
import com.jvyou.app.ds.service.LessonService;
import com.jvyou.app.ds.utils.login.LoginContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 驾校课时主表(Lesson)表服务实现类
 *
 * @author 橘柚
 * @since 2025-04-11 13:19:59
 */
@Service("lessonService")
@RequiredArgsConstructor
public class LessonServiceImpl extends ServiceImpl<LessonMapper, Lesson> implements LessonService {

    private final LessonMapper lessonMapper;
    private final CoachMapper coachMapper;
    private final LicenseTypeMapper licenseTypeMapper;
    private final CourseSubjectMapper courseSubjectMapper;
    private final UserMapper userMapper;
    private final StudentMapper studentMapper;
    private final LessonStudentMapper lessonStudentMapper;

    private QueryWrapper<Lesson> getWrapper(LessonDto lessonDto) {
        QueryWrapper<Lesson> ew = new QueryWrapper<>();
        WrapperTool.notEmptyEq(ew, Lesson::getStatus, lessonDto.getStatus());  // 课程状态
        WrapperTool.notEmptyEq(ew, Lesson::getCourseTypeId, lessonDto.getCourseTypeId());  // 课程类型
        WrapperTool.notEmptyEq(ew, Lesson::getLicenseTypeId, lessonDto.getLicenseTypeId());  // 驾照类型
        if (lessonDto.getDateRange() != null && lessonDto.getDateRange().length == 2) {  // 时间范围
            WrapperTool.betweenDateRange(ew, "start_time", lessonDto.getDateRange()[0], lessonDto.getDateRange()[1]);
        }
        return ew;
    }
    @SuppressWarnings("all")
    @Override
    public PageResult<Lesson> pageLesson(LessonDto lessonDto) {
        IPage<Lesson> page = new Page<>(lessonDto.getCurrent(), lessonDto.getPageSize());
        page = page(page, getWrapper(lessonDto));
        List<Lesson> records = page.getRecords();
        // 组装课程基本信息
        for (Lesson lesson : records) {
            // 查询教练信息
            Coach coach = coachMapper.selectById(lesson.getCoachId());
            lesson.setCoachName(coach.getName());
            // 查询用户信息
            User user = userMapper.selectById(coach.getUserId());
            lesson.setCoachAvatar(user.getAvatar());
            // 查询驾照类型
            LicenseType licenseType = licenseTypeMapper.selectById(lesson.getLicenseTypeId());
            lesson.setLicenseTypeCode(licenseType.getLicenseCode());
            lesson.setLicenseTypeName(licenseType.getLicenseName());
            lesson.setLicenseTypColor(licenseType.getColor());
            // 查询课程类型
            CourseSubject courseSubject = courseSubjectMapper.selectById(lesson.getCourseTypeId());
            lesson.setCourseSubjectName(courseSubject.getSubjectName());
            lesson.setCourseSubjectColor(courseSubject.getColor());
            if (LoginContext.isLogin()) {
                Long userId = LoginContext.getUserId();
                Student student = studentMapper.getByUser(userId);
                if (student == null) {
                    throw new AppException(HttpCodeEnum.DATA_NOT_EXIST, "学员信息异常，查询不到学员信息");
                }
                // 查询签到状态
                LessonStudent lessonStudent = lessonStudentMapper.selectOne(new LambdaQueryWrapper<LessonStudent>()
                        .eq(LessonStudent::getLessonId, lesson.getId())
                        .eq(LessonStudent::getStudentId, student.getId()));
                if (lessonStudent == null) {
                    continue;
                }
                lesson.setSignInStatus(lessonStudent.getStatus());
            }
        }
        return PageResult.success(page);
    }

    @Override
    public List<Lesson> listLesson(LessonDto lessonDto) {
        return list(getWrapper(lessonDto));
    }



    @Override
    public PageResult<Lesson> getByCoach(LessonDto lessonDto) {
        Long userId = LoginContext.getUserId();
        LoginUser loginUser = LoginContext.getLoginUser();

        LambdaQueryWrapper<Lesson> ew = new LambdaQueryWrapper<>();
        Coach coach = null;
        // 管理员可以查看全部
        if (!loginUser.getType().equals(UserType.ADMIN)) {
            coach = coachMapper.getByUserId(userId);
            if (coach == null) {
                throw new AppException(HttpCodeEnum.DATA_NOT_EXIST, "教练信息异常，查询不到教练信息");
            }
            ew.eq(Lesson::getCoachId, coach.getId());
        }

        ew.orderByDesc(Lesson::getStartTime);
        ew.eq(ValueUtil.isNotEmpty(lessonDto.getStatus()), Lesson::getStatus, lessonDto.getStatus());
        ew.eq(lessonDto.getCourseTypeId() != null, Lesson::getCourseTypeId, lessonDto.getCourseTypeId());
        WrapperTool.betweenDateRange(ew, Lesson::getStartTime, lessonDto.getStartTime(), lessonDto.getEndTime());
        IPage<Lesson> page = new Page<>(lessonDto.getCurrent(), lessonDto.getPageSize());
        page = page(page, ew);
        List<Lesson> records = page.getRecords();
        for (Lesson lesson : records) {
            if (coach == null) {
                coach = coachMapper.selectById(lesson.getCoachId());
            }
            lesson.setCoachName(coach.getName());
            // 查询驾照类型
            LicenseType licenseType = licenseTypeMapper.selectById(lesson.getLicenseTypeId());
            lesson.setLicenseTypeCode(licenseType.getLicenseCode());
            lesson.setLicenseTypeName(licenseType.getLicenseName());
            // 查询课程类型
            CourseSubject courseSubject = courseSubjectMapper.selectById(lesson.getCourseTypeId());
            lesson.setCourseSubjectName(courseSubject.getSubjectName());
        }
        return PageResult.success(page);
    }

    @Override
    public Lesson addLesson(Lesson lesson) {
        Coach coach = coachMapper.getByUserId(LoginContext.getUserId());
        if (coach == null) {
            throw new AppException(HttpCodeEnum.DATA_NOT_EXIST, "教练信息异常，查询不到教练信息");
        }
        lesson.setCoachId(coach.getId());
        save(lesson);
        return lesson;
    }

    @SuppressWarnings("all")
    @Override
    public PageResult<Lesson> getByStudent(LessonDto lessonDto) {
        Long userId = LoginContext.getUserId();
        LoginUser loginUser = LoginContext.getLoginUser();
        if (!loginUser.getType().equals(UserType.STUDENT)) {
            throw new AppException(HttpCodeEnum.USER_TYPE_ERROR);
        }
        Student student = studentMapper.getByUser(userId);
        if (student == null) {
            throw new AppException(HttpCodeEnum.DATA_NOT_EXIST, "学员信息异常，查询不到学员信息");
        }
        LambdaQueryWrapper<Lesson> ew = new LambdaQueryWrapper<>();
        ew.inSql(Lesson::getId, "SELECT lesson_id FROM ds_lesson_student WHERE student_id='" + student.getId() + "'");
        ew.orderByDesc(Lesson::getStartTime);
        IPage<Lesson> page = new Page<>(lessonDto.getCurrent(), lessonDto.getPageSize());
        page = page(page, ew);
        List<Lesson> records = page.getRecords();
        for (Lesson lesson : records) {
            // 查询教练信息
            Coach coach = coachMapper.selectById(lesson.getCoachId());
            lesson.setCoachName(coach.getName());
            // 查询用户信息
            User user = userMapper.selectById(coach.getUserId());
            lesson.setCoachAvatar(user.getAvatar());

            // 查询驾照类型
            LicenseType licenseType = licenseTypeMapper.selectById(lesson.getLicenseTypeId());
            lesson.setLicenseTypeCode(licenseType.getLicenseCode());
            lesson.setLicenseTypeName(licenseType.getLicenseName());
            lesson.setLicenseTypColor(licenseType.getColor());
            // 查询课程类型
            CourseSubject courseSubject = courseSubjectMapper.selectById(lesson.getCourseTypeId());
            lesson.setCourseSubjectName(courseSubject.getSubjectName());
            lesson.setCourseSubjectColor(courseSubject.getColor());
            // 查询签到状态
            LessonStudent lessonStudent = lessonStudentMapper.selectOne(new LambdaQueryWrapper<LessonStudent>()
                    .eq(LessonStudent::getLessonId, lesson.getId())
                    .eq(LessonStudent::getStudentId, student.getId()));
            lesson.setSignInStatus(lessonStudent.getStatus());
        }
        return PageResult.success(page);
    }


}
